package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"version-hub/cache"
	"version-hub/models"
	"version-hub/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不可为空",
		})
		return
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不存在此用户",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	data := models.Article{
		Title:   title,
		Content: content,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	var article models.Article
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	models.DB.Where("id=?", data.ID).First(&article)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	cache.Rdb.Set(cache.Ctx, redis_key, cacheData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	err := models.DB.Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	err := models.DB.Where("id=?", id).Delete(&article, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "add_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "4"))
	offset := (page - 1) * size
	var count int64
	var article []models.Article
	models.DB.Model(&article).Count(&count)

	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"article": article,
			"count":   count,
		},
	})
}
